angular.module('nonghua.controllers.distributor', [])
    .controller('InvoiceStatsCtrl', function ($scope,$http,$ionicLoading,$ionicPopover,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own invoice'),
            add:$rootScope.user_access('add invoice'),
            stats:$rootScope.user_access('view invoice stats'),
        }
        $scope.moduleTitle = "销售统计信息 （环比）";
        $scope.moduleName = "invoice";
        $scope.statsMsg= "";
        /*******************************图表相关************************************/
        $scope.optionQoQ_sales = {
            title : {
                text: '销售',
            },
            tooltip : {
                trigger: 'axis',
                formatter: '{c}'
            },
            legend: {
                data:[]
            },
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    boundaryGap : false,
                    categories : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : []
        };
        // popover
        _init_popover($scope,$ionicPopover);
        //date
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:2
        };
        $scope.getSalesStats = function($event){
            if(empty(geoName)){
                alert("地理位置 必选.");
                return;
            }
            if($scope.dateOption.year==""){
                alert("年份 必选.");
                return;
            }
            if($scope.dateOption.month==""){
                alert("月份 必选.");
                return;
            }

            $scope.openPopover($event);

            $scope.barChartQoQ_sales = echarts.init(document.getElementById('divQoQ_sales'));
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });


            var params = [];
            var geoLevel = getGeoLevel(geoName);
            var nationalID = getNationalID(geoLevel, geoName);
            params.push('parameters[geo_name]=' + (!geoName ? geoChain[geoChain.length-1] : geoName));
            params.push('parameters[geo_level]=' + geoLevel);
            params.push('parameters[national_id]=' + nationalID);
            params.push('parameters[year]=' + $scope.dateOption.year);
            params.push('parameters[month]=' + $scope.dateOption.month);
            $http.get( Drupal.settings.site_path+ '/api/sales?' + params.join('&'))
                .success(function (json) {
                    $ionicLoading.hide();

                    $scope.optionQoQ_sales.legend.data = json.legend;
                    $scope.optionQoQ_sales.xAxis[0].data = json.xAxis;
                    $scope.optionQoQ_sales.series = json.yAxis;

                    $scope.barChartQoQ_sales.setOption($scope.optionQoQ_sales, true);
                })

        };
        initMap("#map_previous", "#map_next",$http);
    })
    .controller('MonthlyReportStatsCtrl', function ($scope,$http,$ionicLoading,$ionicPopover,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own monthly_report'),
            add:$rootScope.user_access('add monthly_report'),
            stats:$rootScope.user_access('view monthly_report stats'),
        }
        $scope.moduleTitle = "月清月结";
        $scope.moduleName = "monthly_report";
        $scope.statsMsg= "";
        /*******************************图表相关************************************/
        $scope.optionThisMonthDelivery = {
            show : true,
            tooltip : {
                trigger: 'axis'
            },
            legend: {
                data:['当月发货']
            },
            toolbox: {
                show : false
            },
            color : [ '#00a0a0' ],
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    data : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    name: '当月发货',
                    type: 'bar',
                    barWidth: 30,
                    data: []
                }
            ]
        };
        $scope.optionThisMonthSales = {
            show : true,
            tooltip : {
                trigger: 'axis'
            },
            legend: {
                data:['当月销售']
            },
            toolbox: {
                show : false
            },
            color : [ '#00a0a0' ],
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    data : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    name: '当月销售',
                    type: 'bar',
                    barWidth: 30,
                    data: []
                }
            ]
        };
        $scope.optionAccumulatedSales = {
            show : true,
            tooltip : {
                trigger: 'axis'
            },
            legend: {
                data:['累计销售']
            },
            toolbox: {
                show : false
            },
            color : [ '#00a0a0' ],
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    axisLabel: {
                        interval: 0
                    },
                    data : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    name: '累计销售',
                    type: 'bar',
                    barWidth: 30,
                    data: []
                }
            ]
        };
        $scope.optionThisMonthStock = {
            show : true,
            tooltip : {
                trigger: 'axis'
            },
            legend: {
                data:['库存数量']
            },
            toolbox: {
                show : false
            },
            color : [ '#00a0a0' ],
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    data : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    name: '库存数量',
                    type: 'bar',
                    barWidth: 30,
                    data: []
                }
            ]
        };

        // popover
        _init_popover($scope,$ionicPopover);

        //date
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:2
        };
        $scope.getDistributorMonthlyReportStat = function($event){
            if(empty(geoName)){
                alert("地理位置 必选.");
                return;
            }
            if($scope.dateOption.year==""){
                alert("年份 必选.");
                return;
            }
            if($scope.dateOption.month==""){
                alert("月份 必选.");
                return;
            }

            $scope.openPopover($event);

            $scope.barChartThisMonthDelivery = echarts.init(document.getElementById('divThisMonthDelivery'));
            $scope.barChartThisMonthSales = echarts.init(document.getElementById('divThisMonthSales'));
            $scope.barChartAccumulatedSales = echarts.init(document.getElementById('divAccumulatedSales'));
            $scope.barChartThisMonthStock = echarts.init(document.getElementById('divThisMonthStock'));
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });


            var params = [];
            var geoLevel = getGeoLevel(geoName);
            var nationalID = getNationalID(geoLevel, geoName);
            params.push('parameters[geo_name]=' + (!geoName ? geoChain[geoChain.length-1] : geoName));
            params.push('parameters[geo_level]=' + geoLevel);
            params.push('parameters[national_id]=' + nationalID);
            params.push('parameters[year]=' + $scope.dateOption.year);
            params.push('parameters[month]=' + $scope.dateOption.month);
            $http.get( Drupal.settings.site_path+ '/api/sales_monthly_report?' + params.join('&'))
                .success(function (json) {
                    $ionicLoading.hide();

                    $scope.optionThisMonthDelivery.xAxis[0].data = json.thisMonthDelivery.times;
                    $scope.optionThisMonthDelivery.series[0].data = json.thisMonthDelivery.values;
                    $scope.barChartThisMonthDelivery.setOption($scope.optionThisMonthDelivery, true);

                    $scope.optionThisMonthSales.xAxis[0].data = json.thisMonthSales.times;
                    $scope.optionThisMonthSales.series[0].data = json.thisMonthSales.values;
                    $scope.barChartThisMonthSales.setOption($scope.optionThisMonthSales, true);

                    $scope.optionAccumulatedSales.xAxis[0].data = json.accumulatedSales.times;
                    $scope.optionAccumulatedSales.series[0].data = json.accumulatedSales.values;
                    $scope.barChartAccumulatedSales.setOption($scope.optionAccumulatedSales, true);

                    $scope.optionThisMonthStock.xAxis[0].data = json.thisMonthStock.times;
                    $scope.optionThisMonthStock.series[0].data = json.thisMonthStock.values;
                    barChartThisMonthStock.setOption($scope.optionThisMonthStock, true);
                })

        };
        initMap("#map_previous", "#map_next",$http);
    })
    .controller('StockInfoStatsCtrl', function ($scope,$http,$ionicLoading,$ionicPopover,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own stock_info'),
            add:$rootScope.user_access('add stock_info'),
            stats:$rootScope.user_access('view stock_info stats'),
        }
        $scope.moduleTitle = "库存信息";
        $scope.moduleName = "stock_info";
        $scope.statsMsg= "";
        /*******************************图表相关************************************/

        $scope.optionYoY_thisMonthStock = {
            show : true,
            tooltip : {
                trigger: 'axis'
            },
            toolbox: {
                show : false
            },
            color : [ '#00a0a0' ],
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    data : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    type: 'bar',
                    data: []
                }
            ]
        };
        $scope.optionQoQ_thisMonthStock = {
            title : {
                //text: '库存',
            },
            tooltip : {
                trigger: 'axis',
            },
            legend: {
                data:[]
            },
            calculable : false,
            xAxis : [
                {
                    type : 'category',
                    boundaryGap : false,
                    data : []
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [

            ]
        };
        // popover
        _init_popover($scope,$ionicPopover);

        //date
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:2
        };
        $scope.getDistributorStockInfoStat = function($event){
            if(empty(geoName)){
                alert("地理位置 必选.");
                return;
            }
            if($scope.dateOption.year==""){
                alert("年份 必选.");
                return;
            }
            if($scope.dateOption.month==""){
                alert("月份 必选.");
                return;
            }

            $scope.openPopover($event);
            $scope.barChartYoY_thisMonthStock = echarts.init(document.getElementById('divYoY_thisMonthStock'));
            $scope.barChartQoQ_thisMonthStock = echarts.init(document.getElementById('divQoQ_thisMonthStock'));
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            var params = [];
            var geoLevel = getGeoLevel(geoName);
            var nationalID = getNationalID(geoLevel, geoName);
            params.push('parameters[geo_name]=' + (!geoName ? geoChain[geoChain.length-1] : geoName));
            params.push('parameters[geo_level]=' + geoLevel);
            params.push('parameters[national_id]=' + nationalID);
            params.push('parameters[year]=' + $scope.dateOption.year);
            params.push('parameters[month]=' + $scope.dateOption.month);
            $http.get( Drupal.settings.site_path+ '/api/stock_info?' + params.join('&'))
                .success(function (json) {
                    $ionicLoading.hide();

                    $scope.optionYoY_thisMonthStock.xAxis[0].data = json.YoY_thisMonthStock.times;
                    $scope.optionYoY_thisMonthStock.series[0].data = json.YoY_thisMonthStock.values;
                    $scope.barChartYoY_thisMonthStock.setOption($scope.optionYoY_thisMonthStock, true);

                    $scope.optionQoQ_thisMonthStock.legend.data = json.QoQ_thisMonthSales.legend;
                    $scope.optionQoQ_thisMonthStock.xAxis[0].data = json.QoQ_thisMonthSales.xAxis;
                    $scope.optionQoQ_thisMonthStock.series = json.QoQ_thisMonthSales.yAxis;
                    $scope.barChartQoQ_thisMonthStock.setOption($scope.optionQoQ_thisMonthStock, true);
                })

        };
        initMap("#map_previous", "#map_next",$http);
    })
    .controller('InvoiceListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own invoice'),
            add:$rootScope.user_access('add invoice'),
            stats:$rootScope.user_access('view invoice stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "销售发票";
        $scope.moduleName = "invoice";
        listCtrl($scope, $rootScope,"id","invoiceList", "invoice_list", $ionicSideMenuDelegate);
    })

    .controller('InvoiceDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        var listStateName = "invoice-list";
        var resourceName = "invoice_add";
        $scope.listName = "invoiceList";
        $scope.moduleTitle = "销售数据";
        $scope.moduleName = "invoice";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own invoice'),
            add:$rootScope.user_access('add invoice'),
            stats:$rootScope.user_access('view invoice stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            init_addr_id:!empty($scope.detail) && !empty($scope.detail.delivery_addr_id) ? $scope.detail.delivery_addr_id : "",
            level:3
        };
        $scope.distributorOption={
            value:'',
            params:
            {
                action: "get_distributor_all" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'经销商',
            initValue:!empty($scope.detail) && !empty($scope.detail.distributor_id) ? $scope.detail.distributor_id : ''
        };
        $scope.salesmanOption={
            value:'',
            params:
            {
                action: "get_employee" //'plant','fertilizer','product','brand','sales_type','department_employee','sacfvariety','employee'
            },
            label:'销售员',
            initValue:!empty($scope.detail) && !empty($scope.detail.salesman_id) ? $scope.detail.salesman_id : ''
        };
        $scope.salesTypeOption={
            value:'',
            params:
            {
                action: "get_sales_type" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'销售类型',
            initValue:!empty($scope.detail) && !empty($scope.detail.sales_type_id) ? $scope.detail.sales_type_id : ''
        };

        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.invoice_date) ? get_year_month_day_from_date($scope.detail.invoice_date)['year'] : '',
            initMonth:!empty($scope.detail) && !empty($scope.detail.invoice_date) ? get_year_month_day_from_date($scope.detail.invoice_date)['month'] : '',
            initDay:!empty($scope.detail) && !empty($scope.detail.invoice_date) ? get_year_month_day_from_date($scope.detail.invoice_date)['day'] : '',
            month:'',
            day:'',
            level:3
        };
        $scope.sacfvarietyOption={
            value:'',
            params:
            {
                action: "get_sacfvariety" //'plant','fertilizer','product','brand','sales_type','department_employee',''sacfvariety'
            },
            label:'化肥品种',
            initValue:!empty($scope.detail) && !empty($scope.detail.sacfvariety_id) ? $scope.detail.sacfvariety_id : ''
        };
        $scope.inoroutOption={
            inoroutSource:[{id:"关内",label:"关内"},{id:"关外",label:"关外"}],
            value:!empty($scope.detail) && !empty($scope.detail.inorout) ? $scope.detail.inorout : '关外'
        };
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                id: !empty($scope.id) ? $scope.id : "",
                invoice_id:$scope.detail.invoice_id ,
                delivery_addr_id: _get_address_id($scope.addressOption),
                distributor_id: $scope.distributorOption.value,
                sacfvariety_id:  $scope.sacfvarietyOption.value,
                salesman_id:  $scope.salesmanOption.value,
                invoice_date: $scope.dateOption.year+"-"+$scope.dateOption.month+"-"+$scope.dateOption.day,
                sales_type_id:$scope.salesTypeOption.value,
                quantity: $scope.detail.quantity,
                station_name: $scope.detail.station_name,
                railway_bureau: $scope.detail.railway_bureau,
                inorout: $scope.inoroutOption.value,
            };
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        //if ($scope.id != "") {
                        //    $scope.detail.year = params.year;
                        //    $scope.detail.month = params.month;
                        //    $scope.detail.distributor_id = params.distributor_id;
                        //    $scope.detail.distributor_name =get_select_name($scope.distributorOption.optionSource,params.distributor_id);
                        //    $scope.detail.salesman_id = params.salesman_id;
                        //    $scope.detail.salesman =get_select_name($scope.salesmanOption.optionSource,params.salesman_id);
                        //    $scope.detail.delivery_addr_id = params.delivery_addr_id;
                        //    $scope.detail.sales_type_id = params.sales_type_id;
                        //    $scope.detail.sales_date = params.sales_date;
                        //    $scope.detail.inorout = params.inorout;
                        //    $scope.detail.sacfvariety_id = params.sacfvariety_id;
                        //    $scope.detail.variety_name =get_select_name($scope.sacfvarietyOption.optionSource,params.sacfvariety_id);
                        //    $rootScope[$scope.listName][$scope.id] = $scope.detail;
                        //}
                        //$state.go(listStateName);
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    
    .controller('StockInfoListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own stock_info'),
            add:$rootScope.user_access('add stock_info'),
            stats:$rootScope.user_access('view stock_info stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "库存信息";
        $scope.moduleName = "stock_info";
        listCtrl($scope, $rootScope,"stock_info_id","stockInfoList", "stock_info_list", $ionicSideMenuDelegate);
    })

    .controller('StockInfoDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        var listStateName = "stock-info-list";
        var resourceName = "stock_info_add";
        $scope.listName = "stockInfoList";
        $scope.moduleTitle = "库存信息";
        $scope.moduleName = "stock_info";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own stock_info'),
            add:$rootScope.user_access('add stock_info'),
            stats:$rootScope.user_access('view stock_info stats'),
        }
        $scope.distributorOption={
            value:'',
            params:
            {
                action: "get_distributor_all" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'经销商',
            initValue:!empty($scope.detail) && !empty($scope.detail.distributor_id) ? $scope.detail.distributor_id : ''
        };

        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.year) ? $scope.detail.year : '',
            initMonth:!empty($scope.detail) && !empty($scope.detail.month) ? $scope.detail.month : '',
            month:'',
            day:'',
            level:2
        };
        $scope.sacfvarietyOption={
            value:'',
            params:
            {
                action: "get_sacfvariety" //'plant','fertilizer','product','brand','sales_type','department_employee',''sacfvariety'
            },
            label:'化肥品种',
            initValue:!empty($scope.detail) && !empty($scope.detail.sacfvariety_id) ? $scope.detail.sacfvariety_id : ''
        };

        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                stock_info_id:!empty($scope.id) ? $scope.id : 0,
                year:  $scope.dateOption.year,
                month: $scope.dateOption.month,
                distributor_id: $scope.distributorOption.value,
                sacfvariety_id:  $scope.sacfvarietyOption.value,
                last_month_stock: $scope.detail.last_month_stock,
                return_stock:  $scope.detail.return_stock,
                this_month_instock:  $scope.detail.this_month_instock,
                this_month_outstock:  $scope.detail.this_month_outstock,
                this_month_stock:  $scope.detail.this_month_stock,
                this_month_sales:  $scope.detail.this_month_sales,
                details: $scope.detail.details,
            };
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        //if ($scope.id != "") {
                        //    $scope.detail.year = params.year;
                        //    $scope.detail.month = params.month;
                        //    $scope.detail.distributor_id = params.distributor_id;
                        //    $scope.detail.distributor_name =get_select_name($scope.distributorOption.optionSource,params.distributor_id);
                        //    $scope.detail.sacfvariety_id = params.sacfvariety_id;
                        //    $scope.detail.variety_name =get_select_name($scope.sacfvarietyOption.optionSource,params.sacfvariety_id);
                        //    $rootScope[$scope.listName][$scope.id] = $scope.detail;
                        //}
                        //$state.go(listStateName);
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })

    .controller('MonthlyReportListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own monthly_report'),
            add:$rootScope.user_access('add monthly_report'),
            stats:$rootScope.user_access('view monthly_report stats'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:3
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:1
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                year: $scope.dateOption.year,
            };
        };
        $scope.moduleTitle = "月清月结";
        $scope.moduleName = "monthly_report";
        listCtrl($scope, $rootScope,"monthly_report_id","monthlyReportList", "monthly_report_list", $ionicSideMenuDelegate);
    })

    .controller('MonthlyReportDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        var listStateName = "monthly-report-list";
        var resourceName = "monthly_report_add";
        $scope.listName = "monthlyReportList";
        $scope.moduleTitle = "月清月结";
        $scope.moduleName = "monthly_report";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own monthly_report'),
            add:$rootScope.user_access('add monthly_report'),
            stats:$rootScope.user_access('view monthly_report stats'),
        }
        $scope.distributorOption={
            value:'',
            params:
            {
                action: "get_distributor_all" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'经销商',
            initValue:!empty($scope.detail) && !empty($scope.detail.distributor_id) ? $scope.detail.distributor_id : ''
        };

        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.year) ? $scope.detail.year : '',
            initMonth:!empty($scope.detail) && !empty($scope.detail.month) ? $scope.detail.month : '',
            month:'',
            day:'',
            level:2
        };

        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                monthly_report_id: !empty($scope.id) ? $scope.id : 0,
                year:  $scope.dateOption.year,
                month: $scope.dateOption.month,
                distributor_id: $scope.distributorOption.value,

                this_month_received_payment: !empty( $scope.detail.this_month_received_payment)? $scope.detail.this_month_received_payment:'0.00',
                accounts_receivable:          !empty( $scope.detail.accounts_receivable)? $scope.detail.accounts_receivable:'0.00',
                payment_overdue:               !empty( $scope.detail.payment_overdue)? $scope.detail.payment_overdue:'0.00',
                payment_credit:                 !empty( $scope.detail.payment_credit)? $scope.detail.payment_credit:'00',
                paulin_number:                  !empty( $scope.detail.paulin_number)? $scope.detail.paulin_number:'0.00',
                paulin_overdue:              $scope.detail.paulin_overdue,
                damage_info:                 $scope.detail.damage_info,
                payment_info:                $scope.detail.payment_info,
                promotion_info:              $scope.detail.promotion_info,
                unqualified_info:            $scope.detail.unqualified_info,
                accident_info:               $scope.detail.accident_info,
                pending_issues:              $scope.detail.pending_issues,
                competitor_info:             $scope.detail.competitor_info,
                next_month_task:             $scope.detail.next_month_task,
            };
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        //if ($scope.id != "") {
                        //    $scope.detail.year = params.year;
                        //    $scope.detail.month = params.month;
                        //    $scope.detail.distributor_id = params.distributor_id;
                        //    $scope.detail.distributor_name =get_select_name($scope.distributorOption.optionSource,params.distributor_id);
                        //    $scope.detail.salesman_id = params.salesman_id;
                        //    $scope.detail.salesman =get_select_name($scope.salesmanOption.optionSource,params.salesman_id);
                        //    $scope.detail.delivery_addr_id = params.delivery_addr_id;
                        //    $scope.detail.sales_type_id = params.sales_type_id;
                        //    $scope.detail.sales_date = params.sales_date;
                        //    $scope.detail.inorout = params.inorout;
                        //    $scope.detail.sacfvariety_id = params.sacfvariety_id;
                        //    $scope.detail.variety_name =get_select_name($scope.sacfvarietyOption.optionSource,params.sacfvariety_id);
                        //    $rootScope[$scope.listName][$scope.id] = $scope.detail;
                        //}
                        //$state.go(listStateName);
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    });

